package com.gpt.article.controller;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import com.gpt.article.domain.GptSpiderArticle;
import com.gpt.article.service.impl.taskHandle.testTask.ClassTaskTest;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.gpt.article.domain.GptTopicTitle;
import com.gpt.article.service.IGptTopicTitleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 主题文章Controller
 * 
 * @author zhuzi
 * @date 2023-11-26
 */
@RestController
@RequestMapping("/article/topicTitle")
public class GptTopicTitleController extends BaseController
{
    @Autowired
    private IGptTopicTitleService gptTopicTitleService;
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询主题文章列表
     */
    @PreAuthorize("@ss.hasPermi('article:topicTitle:list')")
    @GetMapping("/list")
    public TableDataInfo list(GptTopicTitle gptTopicTitle)
    {
        startPage();
        List<GptTopicTitle> list = gptTopicTitleService.selectGptTopicTitleList(gptTopicTitle);
        return getDataTable(list);
    }

    /**
     * 导出主题文章列表
     */
    @PreAuthorize("@ss.hasPermi('article:topicTitle:export')")
    @Log(title = "主题文章", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GptTopicTitle gptTopicTitle)
    {
//        List<GptTopicTitle> list = gptTopicTitleService.selectGptTopicTitleList(gptTopicTitle);
//        ExcelUtil<GptTopicTitle> util = new ExcelUtil<GptTopicTitle>(GptTopicTitle.class);
//        util.exportExcel(response, list, "主题文章数据");

        //暂时
        ClassTaskTest.getChongfu();
    }

    /**
     * 获取主题文章详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:topicTitle:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(gptTopicTitleService.selectGptTopicTitleById(id));
    }

    /**
     * 新增主题文章
     */
    @PreAuthorize("@ss.hasPermi('article:topicTitle:add')")
    @Log(title = "主题文章", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GptTopicTitle gptTopicTitle)
    {
        return toAjax(gptTopicTitleService.insertGptTopicTitle(gptTopicTitle));
    }

    /**
     * 修改主题文章
     */
    @PreAuthorize("@ss.hasPermi('article:topicTitle:edit')")
    @Log(title = "主题文章", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GptTopicTitle gptTopicTitle)
    {
        return toAjax(gptTopicTitleService.updateGptTopicTitle(gptTopicTitle));
    }

    /**
     * 删除主题文章
     */
    @PreAuthorize("@ss.hasPermi('article:topicTitle:remove')")
    @Log(title = "主题文章", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gptTopicTitleService.deleteGptTopicTitleByIds(ids));
    }



    /**
     * 上传主题内容
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "上传主题内容", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String classId, String className,
                                 String prompts,String outlineId,String outlineName,String language) throws Exception {

        String operName = getUsername();
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", url);
        ajax.put("fileName", fileName);
        ajax.put("newFileName", FileUtils.getName(fileName));
        ajax.put("originalFilename", file.getOriginalFilename());
        System.out.println(filePath + "/" + fileName);
        //解析文件
        System.out.println(filePath + "--");
        String tmpfilePath = filePath + fileName.replaceAll("/profile/upload", "");
        File excelFile = new File(tmpfilePath);
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(excelFile);
        List<Map<String, Object>> maps = reader.readAll();
        GptTopicTitle gptTopicTitle = null;
        for(Map map:maps){
//            Set<String> set = map.keySet();
//            for(String key:set){
//                System.out.println(key+"-->"+map.get(key));
                String title  =String.valueOf( map.get("Title"));
                String companies   =String.valueOf( map.get("Companies "));
                gptTopicTitle = new GptTopicTitle();
                gptTopicTitle.setTitle( title );
                gptTopicTitle.setDemandPrompts(companies);
                gptTopicTitle.setClassId(Long.valueOf(classId));
                gptTopicTitle.setClassName(className);
                gptTopicTitle.setOutlineId(Long.valueOf(outlineId));
                gptTopicTitle.setOutlineName(outlineName);
                gptTopicTitle.setLanguage(language);
                gptTopicTitleService.insertGptTopicTitle(gptTopicTitle);
//                break;
//            }
        }
        reader.close();
        return success("成功");
    }

    /**
     * 生成主题内容
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(title = "生成主题内容", businessType = BusinessType.GEN)
    @GetMapping("/startGen/{ids}")
    public AjaxResult startGen(@PathVariable Long[] ids){
        String acc = SecurityUtils.getUsername();
        gptTopicTitleService.genGptTopic(ids,acc);
        return success(true);
    }

//    genManyTopic
    /**
     * 全量洗稿
     *
     * @param map
     *   洗稿参数条件
     */
    @Log(title = "执行全量生成主题任务", businessType = BusinessType.GEN)
    @PostMapping("/tartGenAll")
    public AjaxResult tartGenAll(@RequestBody Map<String,Object> map)
    {
        GptTopicTitle gptTopicTitle = new GptTopicTitle();
        BeanMap beanMap = BeanMap.create(gptTopicTitle);
        beanMap.putAll(map);
        String acc = SecurityUtils.getUsername();
        gptTopicTitleService.genManyTopic(gptTopicTitle,acc);
        return success(true);
    }
    /**
     * 查询文章生成列表
     */
    @GetMapping("/detail/{id}")
    public Map<String,Object> list(@PathVariable("id") Long id)
    {
        Map<String,Object> map = gptTopicTitleService.getAticleMap(id);
        return map;
    }

}
